package com.qst.order.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qst.order.domain.Pay;
import com.qst.order.domain.User;
import com.qst.order.service.PayService;
import com.qst.order.service.UserService;
import com.qst.order.utils.JwtUtil;
import com.qst.order.utils.Result;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;

@RequiredArgsConstructor
@Slf4j
@RestController
@RequestMapping("/api/pay")
public class PayController {

    private final PayService payService;
    private final UserService userService;

    private final JwtUtil jwtUtil;

    @PostMapping
    @Transactional
    public Result pay(@RequestBody Pay pay,@RequestHeader("Authorization")String  token) {//充值
        Integer userId =Integer.parseInt( jwtUtil.getClaim(token, "userId"));
        log.warn("支付信息:{}", pay);
        pay.setPayTime(LocalDateTime.now());
        boolean b = payService.save(pay);
        if (!b) {
            return Result.error("支付失败");
        }
        boolean update = userService.lambdaUpdate().setSql("money=money+" + pay.getAmount())
                .eq(User::getId, userId).update();
        if (!update) {
            return Result.error("更新用户余额失败");
        }

        return Result.success("支付成功");

    }
    @GetMapping("/records")
    public Result<IPage<Pay>> getAccountFlows(
            @RequestParam(defaultValue = "1") Integer page, // 默认第1页
            @RequestParam(defaultValue = "10") Integer pageSize, // 默认每页10条
            @RequestHeader("Authorization")String token,
            @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate, // 开始时间（可选）
            @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate) { // 结束时间（可选）

        // 1. 获取当前登录用户ID（必须，防止越权查询）
        String username = jwtUtil.getClaim(token, "username");
        // 2. 调用Service查询流水
        IPage<Pay> flowPage = null;
        try {
            flowPage = payService.queryUserFlows(
                    username, page, pageSize, startDate, endDate
            );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 3. 返回结果（前端需要records和total字段）
        return Result.success(flowPage);
    }


}
